# -*- coding: UTF-8 -*-
import json
from aliyunsdkcore import client
from aliyunsdkvod.request.v20170321 import GetPlayInfoRequest


def _init_vod_client(accessKeyId, accessKeySecret):
    regionId = 'cn-shanghai'   # 点播服务所在的Region，国内请填cn-shanghai，不要填写别的区域
    connectTimeout = 10        # 连接超时，单位：秒。连接失败默认会自动重试，且最多重试3次
    return client.AcsClient(accessKeyId, accessKeySecret, regionId, auto_retry=True, max_retry_time=3, timeout=connectTimeout)


def _get_play_info(clt, videoId):
    request = GetPlayInfoRequest.GetPlayInfoRequest()
    request.set_accept_format('JSON')
    request.set_VideoId(videoId)
    request.set_AuthTimeout(3600*24)     # 播放地址过期时间（只有开启了URL鉴权才生效），默认为3600秒，支持设置最小值为3600秒
    response = json.loads(clt.do_action(request))
    return response


def get_play_info(video_id, kind=0):
    clt = _init_vod_client('LTAIjzYMUkyGRdpq', 'sTbvM6C50e5Nk69Wn2T3QuPauACuGB')
    play_info_json = _get_play_info(clt, video_id)
    print(play_info_json)
    if 'PlayInfoList' not in play_info_json:
        return ''
    play_info_dict = { info['Definition'] : info for info in play_info_json['PlayInfoList']['PlayInfo'] }
    if kind == 1 and 'OD' in play_info_dict:
        return play_info_dict['OD']

    if 'SD' in play_info_dict:
        return play_info_dict['SD']
    elif 'LD' in play_info_dict:
        return play_info_dict['LD']
    elif 'FD' in play_info_dict:
        return play_info_dict['FD']


if __name__ == '__main__':
    video_id = 'd47b8b256b844b268324a9bf499ff0fa'
    play_info = get_play_info(video_id)
    print(play_info)